 <!--
* description: 手动配车（含输入框）
* author: wangml
* createdDate: 2020-11-24
-->
<template>
  <section class="configcar">
    <el-dialog
      id="configcar"
      v-dialogDrag
      title="手动配车"
      :visible.sync="popupsVisible"
      width="70%"
      :append-to-body="true"
      :lock-scroll="true"
      :before-close="handleClose"
    >
      <dialogHeader
        slot="title"
        :title="'手动配车'"
        :style-type="$store.state.app.dialogType"
      />
      <one-table-template
        ref="multipleTable"
        :dynamic-api-config="dynamicApiConfig"
        :dynamic-buttons="dynamicButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-cols="dynamicTableCols"
        :dynamic-form-fields="formField"
        :dynamic-table-defult-height="350"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :dynamic-api-style="apiStyle"
        :dynamic-page-size="10"
        :refresh-table-key="refreshTableKey"
        :callback-obj="callbackObj"
        @hiddenColData="hiddenColData"
      />
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="mini"
          type="primary"
          :disabled="confirmDisabled"
          icon="iconfont  icon-confirm"
          @click="sendCode"
        >
          {{ $t('sys.button.confirm') }}
        </el-button>
        <el-button
          size="mini"
          type="info"
          @click="setCurrent"
        >
          取消
        </el-button>
        <!-- 确认 -->
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
// import { valueObjectMixins } from '@/components/mixins/valueObjectMixins'
// import { contsMixins } from '@/components/mixins/contsMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/testDriver'
import commApi from '@/api/ve'
export default {
  name: 'TDManualConfigCar',
  components: {
    // lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    dialogHeader: () => import('@/components/dialogHeader'), // 弹窗标题,
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    popupsVisible: { type: Boolean, default: false },
    code: { type: String, default: '' },
    comType: { type: String, default: '' },
    codeField: { type: String, default: '' },
    popupsKey: { type: String, default: '' },
    isMul: { type: Boolean, default: true },
    dynamicEditRowData: { type: Object, default: () => ({}) },
    validrule: {
      type: Object,
      default: () => {}
    }
  },
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      confirmDisabled: true,
      table: null,
      curSelected: {},
      currentRow: {},
      selectData: {},
      clickRowsData: null,
      dynamicApiConfig: api.manualConfigCar,
      apiStyle: 'restful',
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'btnKey1',
            type: 'primary',
            size: 'small',
            name: 'search',
            clickEvent: () => this.queryTable(1),
            position: 'right',
            text: '查询'
          },
          {
            compKey: 'btnKey2',
            type: '',
            size: 'small',
            name: 'reset',
            clickEvent: this.reset,
            position: 'right',
            text: '重置'
          }

        ],

      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '销售计划号：',
              codeField: 'salePlanCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6
            },
            {
              compKey: 'VIN',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6
            },
            {
              compKey: 'stockName',
              labelName: '仓库名称：',
              codeField: 'stockId',
              component: () => import('@/components/org/commonSelect'),
              customObj: { api: commApi.ListOfCityWarehouse, selectType: '1', listQuery: { warehouseId: '1' }},
              oFields: 'stockId,stockName',
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'firstInDlrstockDate',
              labelName: '库存天数：',
              codeField: 'firstInDlrstockDate',
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'carConfigCn',
              labelName: '基础车型：',
              codeField: 'carConfigCN',
              textField: 'carConfigId',
              disabled: true,
              // component: () => import('@/components/org/carTypeConfig'),
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMust: false,
              span: 6
            },
            {
              compKey: 'carColorId',
              labelName: '车身颜色：',
              codeField: 'carColorName',
              textField: 'carColorId',
              component: () => import('@/components/org/commonInput'),
              disabled: true,
              isMust: false,
              span: 6
            },
            {
              compKey: 'carIncolorName',
              labelName: '内饰颜色：',
              codeField: 'carIncolorName',
              textField: 'carIncolorId',
              component: () => import('@/components/org/commonInput'),
              disabled: true,
              isMust: false,
              span: 6
            },
            {
              compKey: 'optionalPagId',
              labelName: '选装包：',
              codeField: 'optionalPagName',
              textField: 'carOptionalpagId',
              component: () => import('@/components/org/commonInput'),
              disabled: true,
              isMust: false,
              span: 6
            }
          ],
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'carSeriesCn',
            label: '车系'
          },
          {
            prop: 'salePlanCode',
            label: '销售计划号'
          },
          {
            prop: 'vin',
            label: 'VIN码'
          },
          {
            prop: 'carConfigCN',
            label: '基础车型'
          },
          {
            prop: 'optionalPagName',
            label: '选装包'
          },
          {
            prop: 'carColorName',
            label: '车身颜色'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色'
          },
          {
            prop: 'firstInDlrstockDate',
            label: '库存天数'
          },
          {
            prop: 'carHouseName',
            label: '仓库名称'
          }
        ],
      refreshTableKey: '0',
      ruleSettingShow: false,

      curPopupsVisible: this.popupsVisible,
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.table === null ? this.foundTable() : ''
          this.handleOneSelect(selection)
          this.selectList = selection
          this.handleSelectionChange(selection)
        },
        onBeforeQuery(fields) {
          fields.variables.firstInDlrstockDate = parseInt(fields.variables.firstInDlrstockDate)
        }
      },
      formField: null,
      selectList: []
    }
  },

  watch: {
    'popupsVisible': {
      handler(val) {
        if (val) {
          // 窗口打开
          const keys = Object.keys(this.formField)
          if (keys.length) {
            for (const [attr, val] of Object.entries(this.dynamicEditRowData)) {
              if (keys.includes(attr)) {
                this.formField[attr] = val === null ? '' : val
              }
            }
          }
          this.$nextTick(() => {
            this.$refs['multipleTable'].queryTable()
          })
        } else {
          // 窗口关闭
        }
      },
      immediate: true
    }
  },
  created() {
    this.genFormField()
  },

  methods: {
    reset() {
      this.formField.salePlanCode = ''
      this.formField.vin = ''
      this.formField.stockId = ''
      this.formField.firstInDlrstockDate = ''
    },
    genFormField() {
      const viewPageCode = this.$route.path
      this.genCodeFiled = this.genUtil(this.tableComponents)
      const formField = this.genCodeFiled('codeField')
      this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    // 查找表格元素
    foundTable() {
      this.$refs.multipleTable.$children.forEach(el => {
        el.$el.className.includes('el-table') ? this.table = el : ''
      })
    },
    // 返回数据处理
    sendCode() {
      // if (this.selectList.length) {
      //
      // } else {
      //   this.$confirm('请先选择数据，在进行配车', '提示')
      //     .then(() => { })
      // }
      const { saleOrderId, SALE_ORDER_D_ID, DLR_ID, updateControlId, updateControlIdD, DELIVERY_DLR_ID
      } = this.dynamicEditRowData
      if (Object.keys(this.curSelected).length) {
        const { salePlanCode, vin, InstoreTime, checkZb, checkAREA, checkHouse,
          updateControlIdS, carStoreId, carStoreIdS, carId, carHouseCodeS, FIRST_IN_HOSTSTOCK_DATE } = this.curSelected
        const OLD_DLR_ID = this.curSelected.DLR_ID
        this.$requestAPI({
          apiUrl: api.ManualCarDistribution.APIUrl,
          variables: { checkZb, checkAREA, checkHouse, InstoreTime, SALE_ORDER_D_ID, DLR_ID, saleOrderId, updateControlId, updateControlIdD, FIRST_IN_HOSTSTOCK_DATE,
            salePlanCode, vin, carId, updateControlIdS, carStoreId, carStoreIdS, carHouseCodeS, DELIVERY_DLR_ID, OLD_DLR_ID
          }
        }).then(res => {
          if (res.result === '1') {
            res.msg ? this.$message(res.msg) : this.$message('手动配车成功!')
            this.$parent.$refs['multipleTable'].queryTable()
            this.$emit('update:popupsVisible', false)
          } else {
            this.$message(res.msg)
          }
        }).catch(err => {
          if (err.response.data.msg) {
            this.$message(err.response.data.msg)
          } else {
            this.$message(err.message)
          }
        })
      } else {
        this.$alert('请先选择一条数据!', '提示')
          .then(() => {})
      }
    },
    // 取消选中高亮
    setCurrent(row) {
      if (this.clickRowsData) {
        const table = this.$refs.multipleTable.$children[3]
        table.setCurrentRow(row)
        this.clickRowsData = null
        // this.$message('已取消选中数据!')
      }
      this.$confirm('还没有选择配车数据，确认关闭吗？')
        .then(_ => {
          this.$emit('update:popupsVisible', false)
        }).catch(_ => { })
    },

    // 设置表格选择框 是否禁用
    // getSelectable(row, index) {
    // },
    selectRowsData(val) {
      this.clickRowsData = val
    },

    // 设置表格单选
    handleOneSelect(selection) {
      if (selection.length === 0) { this.selectData = {}; return }
      const lastIndex = selection.length - 1
      this.selectData = selection[lastIndex]
      selection.forEach((sel, idx) => {
        lastIndex !== idx ? this.table.toggleRowSelection(sel, false) : this.curSelected = sel
      })
    },
    handleSelectionChange(selection) {
      if (selection && selection.length > 0) {
        this.confirmDisabled = false
      } else {
        this.confirmDisabled = true
      }
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },
    handleClose() {
      const message = '确认关闭？'
      // this.selectData.hasOwnProperty('index') ? message = '确认关闭？' : message = '还未选择车型配置，确认关闭？'
      this.$confirm(`${message}`)
        .then(_ => {
          this.$emit('update:popupsVisible', false)
          this.table.toggleRowSelection(this.curSelected, false)
          done()
        })
        .catch(_ => {})
    },
    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    }
  }
}
</script>

<style lang="css" scoped>
  >>>div.el-table__empty-block{
    height: 200px;
  }
  div.el-table__body-wrapper.is-scrolling-none{
    height: 200px;
  }
  >>>.el-table__header .el-checkbox{
    display:none
  }
  .dialog-footer {
    float: right;
  }
  >>>.el-dialog__footer {
    overflow: hidden;
    padding: 10px 24px;
  }
</style>
